<template>
    <div class="editor">
        <TinymceEditor v-model="myValue" :init="completeSetting" :disabled="disabled" />
        <el-dialog title="添加多张图片" :visible.sync="dialogVisible" width="60%">
            <el-upload :action="uploadAction" :headers="uploadHeaders" list-type="picture-card" multiple :file-list="fileList" show-file-list :on-change="handleChange" accept=".jpg,.jpeg,.gif,.png">
                <i class="el-icon-plus" />
            </el-upload>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelMultiple">取 消</el-button>
                <el-button type="primary" @click="addMultiple">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import tinymce from 'tinymce/tinymce'
import TinymceEditor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver/theme'
import 'tinymce/icons/default/icons'
import 'tinymce/plugins/autolink'
import 'tinymce/plugins/autoresize'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/hr'
import 'tinymce/plugins/image'
import 'tinymce/plugins/imagetools'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/link'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/media'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/table'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/code'
import 'tinymce/plugins/searchreplace'

export default {
    name: 'Editor',
    components: {
        TinymceEditor
    },
    props: {
        value: {
            type: String,
            default: ''
        },
        setting: {
            type: Object,
            default: () => {}
        },
        disabled: {
            type: Boolean,
            default: false
        }
    },
    data() {
        const that = this
        return {
            dialogVisible: false,
            fileList: [],
            editor: {},
            defaultSetting: {
                language_url: 'tinymce/langs/zh_CN.js',
                language: 'zh_CN',
                skin_url: 'tinymce/skins/ui/oxide',
                min_height: 400,
                max_height: 600,
                selector: 'textarea',
                plugins: 'autolink autoresize fullscreen hr image imagetools insertdatetime link lists media preview table wordcount code searchreplace',
                toolbar:
                    'undo redo | formatselect | bold italic strikethrough forecolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | hr link image media table insertdatetime searchreplace removeformat | preview code fullscreen multipleBtn',
                setup: function(editor) {
                    // 注册一个icon
                    editor.ui.registry.addIcon(
                        'multiple',
                        '<svg t="1640745667286" class="icon" viewBox="0 0 1102 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2564" width="1.5em" height="1.5em"><path d="M888.884513 171.979487l1.024 6.406564 15.596308 108.806564 3.203282 0.183795a196.923077 196.923077 0 0 1 185.842871 199.916308l-0.210051 6.459077-15.937641 320.905846a196.923077 196.923077 0 0 1-206.454154 186.919385l-498.162872-32.295385a196.923077 196.923077 0 0 1-184.162461-193.929846 196.949333 196.949333 0 0 1-134.852923-151.788308l-1.155282-6.931692-47.156513-313.501539a196.923077 196.923077 0 0 1 159.166359-222.995692l6.301538-1.050256L668.278154 11.237744a196.923077 196.923077 0 0 1 220.553846 160.768zM511.684923 613.139692l-3.465846 2.940718-226.67159 210.996513a118.101333 118.101333 0 0 0 97.332513 63.645539l495.195897 32.111589 7.351795 0.262564a118.180103 118.180103 0 0 0 103.581539-60.757333l-162.264616-151.289436a42.089026 42.089026 0 0 0-51.331282-4.726154l-3.36082 2.363077-26.098872 20.48a52.512821 52.512821 0 0 1-69.526974-4.201025l-2.993231-3.255795-85.333333-101.060923-1.654154-1.890462a52.512821 52.512821 0 0 0-70.761026-5.618872z m-106.574769-275.114666a118.153846 118.153846 0 0 0-123.090051 112.981333l-13.548308 316.468513 203.986051-189.833846a105.025641 105.025641 0 0 1 148.427487 5.330051l3.360821 3.807179 85.333333 101.034667 26.072616-20.453744a94.601846 94.601846 0 0 1 118.731487 1.601642l4.174769 3.675897 141.495795 131.938461 15.596308-314.683076a118.153846 118.153846 0 0 0-105.83959-123.405129l-5.513846-0.420102z m279.368205-249.357129l-5.513846 0.630154L183.611077 157.013333a118.153846 118.153846 0 0 0-99.958154 128.866462l0.708923 5.513846L131.492103 604.947692a117.996308 117.996308 0 0 0 61.387487 86.75118l10.450051-244.053334a196.923077 196.923077 0 0 1 205.141333-188.33723l416.794257 23.420718-13.338257-93.131488a118.153846 118.153846 0 0 0-127.448615-100.929641z m168.854974 310.875898a91.897436 91.897436 0 1 1 0 183.794872 91.897436 91.897436 0 0 1 0-183.794872z m0 52.51282a39.384615 39.384615 0 1 0 0 78.769231 39.384615 39.384615 0 0 0 0-78.769231z" p-id="2565"></path></svg>'
                    )
                    // 注册一个自定义的按钮
                    editor.ui.registry.addButton('multipleBtn', {
                        icon: 'multiple',
                        // eslint-disable-next-line no-unused-vars
                        onAction: function(_) {
                            that.dialogVisible = true
                            that.saveImgs = true
                            that.editor = editor
                        }
                    })
                },
                branding: false,
                menubar: false,
                toolbar_mode: 'sliding',
                insertdatetime_formats: ['%Y年%m月%d日', '%H点%M分%S秒', '%Y-%m-%d', '%H:%M:%S'],
                images_upload_handler: (blobInfo, success, failure) => {
                    // 重写tinyMCE编辑器的上传图片
                    // 参考：https://blog.csdn.net/kevinfan2011/article/details/91047062
                    // const img = 'data:image/jpeg;base64,' + blobInfo.base64()
                    let formData = new FormData()
                    formData.append('file', blobInfo.blob())
                    that.$api.post(`${process.env.VUE_APP_API_ROOT}attachment/upload-binary`, formData).then(res => {
                        console.log(res)
                        if (res.code === 0) {
                            success(res.data.data.file_path)
                        } else {
                            failure('上传失败')
                        }
                    })
                }
            },
            myValue: this.value,
            uploadAction: `${process.env.VUE_APP_API_ROOT}attachment/upload-binary`
        }
    },
    computed: {
        completeSetting() {
            return Object.assign(this.defaultSetting, this.setting)
        },
        uploadHeaders() {
            const token = this.$store.state.user.token
            return {
                token
            }
        }
    },
    watch: {
        myValue(newValue) {
            this.$emit('input', newValue)
        },
        value(newValue) {
            this.myValue = newValue
        }
    },
    mounted() {
        tinymce.init({})
    },
    methods: {
        // 添加多图
        addMultiple() {
            this.dialogVisible = false
            let html = ''
            this.fileList.forEach(item => {
                const { file_path, file_width, file_height} = item.response.data.data
                html += `<img src="${file_path}" data-width="${file_width}" data-height="${file_height}" alt="">`
            })
            this.editor.insertContent(html)
            this.saveImgs = false
            this.fileList = []
        },
        handleChange(file, fileList) {
            this.fileList = fileList
        },
        // 取消添加
        cancelMultiple() {
            this.dialogVisible = false
            this.fileList = []
        }
    }
}
</script>

<style lang="scss" scoped>
    ::v-deep .tox-tinymce {
        border: 1px solid #dcdfe6;
        border-radius: 4px;
    }
</style>
